# --*-- coding=utf-8 --*--
import json
import urllib

import requests
from urllib3 import encode_multipart_formdata

from src import Cookie as cookieUtilsClass
from src import Config as config
from src import TestCaseMore


def request(**kwargs):
	"""
	封装requests库，发送请求
	:param kwargs:
	:return:
	"""
	content_type = None
	data = None

	# 获取当前接口url
	url = urllib.parse.urljoin(config.base_url, kwargs.get("url"))

	# 请求方式
	method = str.upper(kwargs.get("method"))

	# 构造请求头和请求体信息
	ct = kwargs.get("content-type")
	data = eval(str(kwargs.get("data")).replace("null", "None").replace("false", "False").replace("true", "True"))
	if ct == "json":
		content_type = "application/json"
		data = json.dumps(data)
	elif ct == "form-urlencoded":
		content_type = "application/x-www-form-urlencoded"
		data = data
	elif ct == "file":
		data = data
		file_path = data.get("file_path")
		data.pop("file_path")
		data['file'] = (file_path.split("/")[-1], open(file_path, 'rb').read())  # 名称，读文件
		encode_data = encode_multipart_formdata(data)
		content_type = encode_data[1]
		data = encode_data[0]

	coo_auth = cookieUtilsClass.cookie_read(kwargs.get("login_name"))
	headers = {
		"Cookie": coo_auth.get("cookie") if config.login_url not in url else "c",
		"authorization": coo_auth.get("authorization"),
		"Content-Type": content_type
	}

	# 发请求
	response = requests.request(method=method, url=url, headers=headers, data=data)
	TestCaseMore().assertEqual(response.status_code, 200, msg=f"{url}，该接口请求失败，响应状态码为：{response.status_code}",
							   log_level="critical")
	return response


if __name__ == '__main__':
	kwargs = {
		"method": "post",
		"url": "/sys/interface-internal/dataUpload/uploadExcelNew",
		"content-type": "file",
		"login_name": "zdh-001",
		"data": {
			"dataTypeCode": "ipDeptNewService",
			"dataTypeName": "城市数据导入",
			"file_path": r"C:\Users\darker\Desktop\配置信息.xlsx"
		}
	}
	request(**kwargs)
